<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use EasyWeChat;
use EasyWeChat\Factory;
use App\Repos\CateRepo;
use App\Repos\ProductRepo;
use App\Repos\UserRepo;
use App\Repos\ShopRepo;
use App\Repos\TagRepo;
use App\Repos\SpecRepo;
use App\Repos\ShopVisitorRepo;
use App\Http\Requests\Api\ApiRequest;
use Redis;

class IndexController extends Controller
{
    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); # 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $app = app('wechat.mini_program');
        $app->server->push(function($message){
            return "欢迎关注!";
        });

        return $app->server->serve();
    }

    public function getOpenid(Request $request)
    {
        $rs['status'] = false;
    	$code = trim($request->code);
    	$mini = EasyWeChat::miniProgram(); // 小程序
		$result = $mini->auth->session($code); // $code 为wx.login里的code
        if(!array_key_exists('openid', $result)) {
            $rs['msg'] = $result['errmsg'];
            return response()->json($rs);
        }
        
        $rs['status'] = true;
        $rs['data']['openid'] = $result['openid'];

        $user = UserRepo::find(['openid'=>$result['openid']]);
        if($user) {
            $rs['data']['token']   = $user->remember_token;
            $rs['data']['user_id'] = $user->id;
            return response()->json($rs);
        }

        $data = array_only($request->all(),['longitude','latitude','avatar','nickname']);
        $data['openid'] = $result['openid'];
        $user =UserRepo::create($data);
        $rs['data']['token']   = $user->remember_token;
        $rs['data']['user_id'] = $user->id;
		return response()->json($rs);	
    }

    public function getShop(ApiRequest $request)
    {
        $rs['status'] = false;
        $items = Redis::georadius("fruit:shops:geo", $request->longitude, $request->latitude, 10000000, "m", "WITHDIST", "ASC");
        //dd($items);
        if(count($items)>0) {
            //dd($items);
            $shop = ShopRepo::find(['id'=>$items[0][0]]);
            //dd($shop,$items[0][0]);
           // 获取店铺优惠券
            $coupons = ShopRepo::coupons($shop->id,$request->user_id);
            $rs['status'] = true;
            $rs['data']['shop_id'] = $shop->id;
            $rs['data']['shop_name'] = $shop->name;
            $rs['data']['min_orderamount']  = object_get($shop,'min_orderamount','20');      
            $rs['data']['dist'] = (int)$items[0][1].'米';
            $rs['data']['coupons'] = $coupons;


           

            return response()->json($rs)->setEncodingOptions(JSON_NUMERIC_CHECK);
        }

        $rs['msg'] = '没有找到合适的商户信息';
        return response()->json($rs);        
    }

    public function shopInfo(ApiRequest $request)
    {
        $rs['status'] = false;
        $shop_id = (int)$request->shop_id;
        $fields = ['id','name','contacter','phone','address','notice','logo'];
        $shop = ShopRepo::find(['id'=>$shop_id],$fields);
        if($shop) {
            $visitor['shop_id'] = $shop_id;
            $visitor['user_id'] = $request->user_id;
            ShopVisitorRepo::create($visitor);

            $rs['status'] = true;
            $rs['data'] = $shop;
            return response()->json($rs);
        }
        return response()->json($rs);
    }

    /**
     * 首页每日鲜果
     */
    public function recProduct(Request $request)
    {
        $rs['status'] = false;
        $where['type_id'] = $request->type;
        $where['shop_id'] = $request->shop_id;
        $where['on_sale'] = 1;
        $num = (int)($request->num?$request->num:10);
        $data = ProductRepo::getList($where,$num);
        if($data) {
            $rs['status'] = true;
            $rs['data'] = $data;
            return response()->json($rs)->setEncodingOptions(JSON_NUMERIC_CHECK);;
        }
        return response()->json($rs)->setEncodingOptions(JSON_NUMERIC_CHECK);;
    }

    /**
     * 购物车特价商品
     */
    public function offerProduct(Request $request)
    {
        $rs['status'] = false;
       
        $where['shop_id'] = $request->shop_id;
        $where['on_sale'] = 1;
        $num = (int)($request->num?$request->num:3);
        $data = ProductRepo::getOfferList($where,$num);
        if($data) {
            $rs['status'] = true;
            $rs['data'] = $data;
            return response()->json($rs)->setEncodingOptions(JSON_NUMERIC_CHECK);;
        }
        return response()->json($rs);
    }

    public function tags(Request $request)
    {
        $rs['status'] = true;
        $where['type'] = 1; //只返回可选tag
        $list = TagRepo::getList($where);
        if($list) {
            $rs['data'] = $list;
            return response()->json($rs);
        }

        $rs['status'] = false;
        return response()->json($rs);

        
    }

    public function specs(Request $request)
    {
        $rs['status'] = true;
        $list = SpecRepo::getList();
        if($list) {
            $rs['data'] = $list;
            return response()->json($rs);
        }

        $rs['status'] = false;
        return response()->json($rs);
    }

    public function getSmallcode(Request $request)
    {
        $value = $request->scene_value;
        $app = EasyWeChat::miniProgram(); // 小程序
        
        $response = $app->app_code->getUnlimit($value, [
            'page'  => 'pages/index/index',
            'width' => 600,
        ]);
      
        if ($response instanceof \EasyWeChat\Kernel\Http\StreamResponse) {
            $filename = $response->save('upload', $value.'.png');
            $rs['status'] = true;
            $rs['data'] = 'upload/'.$filename;
            return response()->json($rs);
        }
       


    }

   
}
